package cn.weekimwee.firstlineofcodeforkotlin.unit6

import android.os.Bundle
import android.util.Log
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_sqlite.*
import org.litepal.LitePal
import org.litepal.crud.DataSupport

/**
 * Created by Wee Kim Wee on 2018/2/20.
 */
class LitePalActivity :BaseActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sqlite)
        createDatabase.setOnClickListener{it.click()}
        addData.setOnClickListener { it.click() }
        query.setOnClickListener { it.click() }
        update.setOnClickListener { it.click() }
        delete.setOnClickListener { it.click() }
    }

    private fun View.click(){
        when(this.id){
            R.id.createDatabase->{
                LitePal.getDatabase()
            }
            R.id.addData->{
                Book(name = "test book",author = "me",pages = 3,press = "unknow",price = 33.33).save()
            }
            R.id.query->{
                val books = DataSupport.findAll(Book::class.java)
                books.forEach {
                    Log.e("eeeee","book name is :${it.name}")
                    Log.e("eeeee","author is :${it.author}")
                    Log.e("eeeee","book page is :${it.pages}")
                    Log.e("eeeee","book price is :${it.price}")
                    Log.e("eeeee","book press is :${it.press}")
                    Log.e("eeeee","book id is :${it.id}")
                }
            }
            R.id.update->{
                DataSupport.find(Book::class.java,1).apply {
                    price = 888.00
                    save()
                }
            }
            R.id.delete->{
                DataSupport.delete(Book::class.java,1)
            }
        }
    }
}